<?php

class __admin_system_fields extends Module {
	
	public function __construct () {
		parent::__construct('system');
	}
	
	public function fields () {
		if (getRequest ('save_position','bool')) {
			$this->savePosition ();
		}
		
		$typeId = getRequest ('param0','int');
		
		if (!$oType = TypesController::getInstance()->getTypeById ($typeId)) {
			throw new NotFound;
		}
		
		$response = $this->getTypeFields ($typeId);
		$response->setTemplate ('system/fields/list');
		
		if (getRequest ('created','bool')) {
			$response->addObject (new SystemMessage (lang('admin_field_created','system')));
		}
		if (getRequest ('saved','bool')) {
			$response->addObject (new SystemMessage (lang('admin_field_saved','system')));
		}
		if (getRequest ('deleted','bool')) {
			$response->addObject (new SystemMessage (lang('admin_field_deleted','system')));
		}
		
		return $response;
	}
	
	public function add_field () {
		return $this->fieldForm ();
	}
	
	public function edit_field () {
		return $this->fieldForm (getRequest ('param0'));
	}
	
	public function delete_field () {
		$this->expectSecureGET ();
		
		if (!$oField = ObjectsController::getInstance()->getObject (TypesController::getInstance()->getTypeByName ('explay_field'), getRequest('param0','int'))) {
			throw new NotFound;
		}
		
		$typeId = $oField->getValue ('type_id');
		
		FieldsController::getInstance()->deleteField ($oField);
		$oField->delete ();
		
		redirect (HTTP_HOST . '/admin/system/fields/' . $typeId . '?deleted');
	}
	
	private function fieldForm ($fieldId = 'new') {
		$oTypeField = TypesController::getInstance()->getTypeByName ('explay_field');

		$assocTypes = array (
			'integer' => 'scalar',
			'float' => 'scalar',
			'guide' => 'guide',
			'multiguide' => 'guide',
			'tags' => 'tags',
			'boolean' => 'scalar',
			'header' => 'scalar',
			'text' => 'scalar',
			'email' => 'scalar',
			'date' => 'scalar',
			'birthdate' => 'scalar',
			'latin' => 'scalar',
			'image' => 'image',
			'object_value' => 'connected'
		);
		
		$info = array ('default' => '');
		
		if ($fieldId == 'new') {
			$typeId = getRequest ('param0','int');
			
			if (!$oType = TypesController::getInstance()->getTypeById ($typeId)) {
				throw new NotFound;
			}
			
			$fieldType = getRequest ('type');
			
			if ($fieldType != 'scalar' && $fieldType != 'guide' && $fieldType != 'tags' && $fieldType != 'connected' && $fieldType != 'image') {
				$fieldType = 'scalar';
			}
		} else {
			if (!$oField = ObjectsController::getInstance()->getObject ($oTypeField, $fieldId)) {
				throw new NotFound;
			}
			
			$info = FieldsController::getInstance()->getFieldSqlInfo ($fieldId);
			
			if ($info['default'] === null) {
				$info['default'] = 'NULL';
			}
			
			$typeId = $oField->getValue ('type_id');
			$fieldType = $assocTypes[$oField->getValue('character')];
		}
		
		$aErrors = array ();
		$aValues = $fieldId == 'new' ? array () : $oField->getValues ();
		
		$form = new Form ($oTypeField, $fieldId);
		$form->buildFromType ();
		
		// СОХРАНЕНИЕ
		if (getRequest ('param1') == 'save') {
			$aValues = $this->getRequestData ($fieldId, $oTypeField);
			
			if (isset ($aValues['maxlength']) && $aValues['maxlength'] == '') {
				//unset ($aValues['maxlength']);
				$aValues['maxlength'] = null;
			}
			if (isset ($aValues['error']) && $aValues['error'] == '') {
				//unset ($aValues['error']);
				$aValues['error'] = null;
			}
			if (isset ($aValues['help']) && $aValues['help'] == '') {
				//unset ($aValues['help']);
				$aValues['help'] = null;
			}
			
			$defaultValue = 'NULL';
			
			if (mb_strlen (getRequest ('default_value')) && !getRequest ('default_value_null','bool')) {
				$defaultValue = getRequest ('default_value');
			}
			
			if ($fieldId == 'new') {
				$oField = new Object ($oTypeField);
				$oField->setValues ($aValues);
				$oField->setValue ('type_id', $typeId);
				
				$aErrors = $this->getFieldValidate ($oField);
				
				if (!count ($aErrors)) {
					FieldsController::getInstance()->createField ($oField, $defaultValue);
					$oField->createNew ();
					
					redirect (HTTP_HOST . '/admin/system/fields/' . $typeId . '?created');
				}
			} else {
				if (isset ($aValues['character'])) {
					unset ($aValues['character']);
				}
				
				$oldName = $oField->getValue ('field_name');
				$oldRequired = $oField->getValue ('required');
				
				$oField->setValues ($aValues);
				$oField->setValue ('type_id', $typeId);
				
				$aErrors = $this->getFieldValidate ($oField, $fieldId);
				
				if (!count ($aErrors)) {
					if ($oldName != $oField->getValue ('field_name') || $oldRequired != $oField->getValue ('required') || $info['default'] != $defaultValue) {
						FieldsController::getInstance()->changeField ($oldName, $oField, $defaultValue);
					}
					
					$oField->save ();

					redirect (HTTP_HOST . '/admin/system/fields/' . $typeId . '?saved');
				}
			}
		}
		
		$form->setValues ($aValues);
		$form->setErrors ($aErrors);
		
		$response = new ModuleResponse;
		$response->setTemplate ('system/fields/form');
		$response->setAttribute ('character-type', $fieldType);
		$response->setAttribute ('type-id', $typeId);
		$response->addObject ($form);
		$response->addObject(new Array2XML ('sql', $info));
		
		return $response;
	}
	
	/**
	 * @param Object $oField
	 * @param integer $id
	 * @return array
	 */
	private function getFieldValidate (Object $oField, $id = false) {
		$aErrors = array ();
		$typeId = 0;
		
		if (TypesController::getInstance()->getTypeById ($oField->getValue ('type_id'))) {
			$typeId = $oField->getValue ('type_id');
		} else {
			$aErrors['type_id'] = lang('error_admin_field_invalid_type','system');
		}
		
		if ($oField->getValue ('field_name') == '') {
			$aErrors['field_name'] = lang('error_admin_field_empty_name','system');
		}
		
		if (!isset ($aErrors['field_name']) && !preg_match("#^[a-zA-Z0-9_]+$#", $oField->getValue ('field_name'))) {
			$aErrors['field_name'] = lang('error_admin_field_name_latin','system');
		}
		
		if (!isset ($aErrors['field_name'])) {
			$sel = new Selection;
			$sel->addType ($oField->getType ());
			$sel->addFilter ('field_name', $oField->getValue ('field_name'));
			$sel->addFilter ('type_id', $typeId);
			if ($id !== false) {
				$sel->addFilter ('id', $id, '!=');
			}
			
			if ($sel->getTotalCount () > 0) {
				$aErrors['field_name'] = lang('error_admin_field_name_already_exists','system');
			}
		}
		
		if ($oField->getValue ('title') == '') {
			$aErrors['title'] = lang('error_admin_field_title_empty','system');
		}
		
		$character = $oField->getValue ('character');
		
		$aCharacters = array ('integer','float','guide','multiguide','tags','boolean','header','text','email','date','birthdate','latin','image','object_value');
		if (!in_array ($character, $aCharacters)) {
			$aErrors['character'] = lang('error_admin_field_incorrect_character','system');
		}
		
		if ($character == 'image') {
			$sel = new Selection;
			$sel->addType (TypesController::getInstance()->getTypeByName ('image_profile'));
			$sel->addFilter ('id', $oField->getValue ('additional_id'));
			
			if ($sel->getTotalCount () == 0) {
				$aErrors['additional_id'] = lang('error_admin_field_image_profile','system');
			}
		} elseif ($character == 'guide' || $character == 'multiguide') {
			$sel = new Selection;
			$sel->addType (TypesController::getInstance()->getTypeByName ('explay_guide'));
			$sel->addFilter ('id', $oField->getValue ('additional_id'));
			
			if ($sel->getTotalCount () == 0) {
				$aErrors['additional_id'] = lang('error_admin_field_guide','system');
			}
		}  elseif ($character == 'object_value') {
			$sel = new Selection;
			$sel->addType (TypesController::getInstance()->getTypeByName ('explay_field'));
			$sel->addFilter ('id', $oField->getValue ('additional_id'));
			
			if ($sel->getTotalCount () == 0) {
				$aErrors['additional_id'] = lang('error_admin_field_connected_field','system');
			}
		}
		
		return $aErrors;
	}
	
	private function savePosition () {
		if (!isset ($_POST['field']) || !is_array ($_POST['field'])) {
			return;
		}
		
		$oTypeField = TypesController::getInstance()->getTypeByName ('explay_field');
		
		$aValues = $_POST['field'];

		foreach ($aValues as $fieldId => $position) {
			if (is_array ($position)) {
				return;
			}
			
			if ($oField = ObjectsController::getInstance()->getObject ($oTypeField, $fieldId)) {
				$oField->setValue ('position', (int) $position);
				$oField->save ();
			}
		}
	}
}